package com.bw.spsy.pay.thread;
import java.util.concurrent.*;

public class Test {

    public static void main(String[] args) {
        // 测试四种拒绝策略
        testRejectionPolicy(new ThreadPoolExecutor.AbortPolicy(), "AbortPolicy");
        testRejectionPolicy(new ThreadPoolExecutor.CallerRunsPolicy(), "CallerRunsPolicy");
        testRejectionPolicy(new ThreadPoolExecutor.DiscardPolicy(), "DiscardPolicy");
        testRejectionPolicy(new ThreadPoolExecutor.DiscardOldestPolicy(), "DiscardOldestPolicy");
    }

    private static void testRejectionPolicy(RejectedExecutionHandler policy, String policyName) {
        System.out.println("\n=== 测试拒绝策略: " + policyName + " ===");

        // 创建一个核心线程数为2，最大线程数为3，队列容量为2的线程池
        // 这样当同时提交超过5个任务时(2核心 + 3队列)，就会触发拒绝策略
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                2, // 核心线程数
                2, // 最大线程数 (为了演示效果，设为与核心线程数相同)
                0, // 空闲线程存活时间
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(3), // 容量为3的队列
                Executors.defaultThreadFactory(),
                policy // 设置拒绝策略
        );

        // 提交6个任务，这会触发拒绝策略
        for (int i = 1; i <= 6; i++) {
            final int taskId = i;
            try {
                executor.execute(() -> {
                    try {
                        System.out.println("任务 " + taskId + " 正在执行，线程: " + Thread.currentThread().getName());
                        Thread.sleep(1000); // 模拟任务执行
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                });
                System.out.println("任务 " + taskId + " 已提交");
            } catch (RejectedExecutionException e) {
                System.out.println("任务 " + taskId + " 被拒绝: " + e.getMessage());
            }
        }

        // 关闭线程池
        executor.shutdown();
        try {
            // 等待所有任务完成
            executor.awaitTermination(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}